package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 用于处理请求
 */
public class DispatcherServlet {
    public void service(HttpRequest request, HttpResponse response){
        String path =request.getUri();
        File file =new File("./webapps"+path);
        String line;
        if (file.isFile() && file.exists()){
            //资源存在
            response.setEntity(file);
            /**
             * 1：通过file获取浏览器实际请求的资源的文件名
             * 2：根据文件名截取后缀名
             * 3：根据后缀名设置Content-Type对应的值（http。txt找对应的）
             */
           Map<String,String> mimeMapping =new HashMap<>();
           mimeMapping.put("html","text/html");
           mimeMapping.put("css","text/css");
           mimeMapping.put("js","application/javascript");
           mimeMapping.put("png","image/png");
           mimeMapping.put("gif","image/gif");
           mimeMapping.put("jpg","image/jpeg");
           String fileName =file.getName();
//           String[] arr =fileName.split("\\.");
//           String type =mimeMapping.get(arr[arr.length-1]);
           String ext =fileName.substring(fileName.lastIndexOf(".")+1);
           String type =mimeMapping.get(ext);
           response.addHeader("Content-Type",type);
           response.addHeader("Content-Length",file.length()+"");//""是为了把file.length的long值转换成字符串
        }else{
            //资源不存在
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file =new File("./webapps/root/404.html");
            response.setEntity(file);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");//""是为了把file.length的long值转换成字符串
        }
        response.addHeader("Server","WebServer");
    }
}
